﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class FlyingItemList : MonoBehaviour
{
    public FlyingItemUI selectedItem { get { return m_SelectedItem; } }
    public FlyingItemUI m_FlyingItemPrefab;
    public GameObject m_Content;
    public List<FlyingItemUI> m_Items = new List<FlyingItemUI> ();
    public DrawFlyitemContent m_DrawFlyItemContent;
    FlyingItemUI m_SelectedItem;
    Weapon m_Weapon;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void Load(Weapon weapon)
    {
        m_Weapon = weapon;
        ClearItems();
        foreach (var i in weapon.flyItems)
        {
            var flyItem = AddItem(i);
            if(m_Weapon.typeID != 0)
                flyItem.m_Sprite = ResourcesManager.Instance.GetWeaponsFlyItemSprite(m_Weapon.typeID, i.flyItemID);

        }
    }
    void ClearItems()
    {
        foreach(var i in m_Items)
        {
            Destroy(i.gameObject);
        }
        m_Items.Clear();
    }

    /// <summary>
    ///  将画板的画放在item里面
    /// </summary>
    public void ApplySelectedItem()
    {
        //  把画放画板上的过程
        if (m_SelectedItem && m_DrawFlyItemContent.m_PaintBoard.image.sprite != null)
        {
            m_SelectedItem.m_Sprite = m_DrawFlyItemContent.m_PaintBoard.image.sprite;
        }
    }
    public void SelectedItem(FlyingItemUI item)
    {
        ApplySelectedItem();
        if (item == null)
        {
            m_DrawFlyItemContent.SetSprite(null);
            m_SelectedItem = null;
            return;
        }
        //  设置子项选中状态的特效
        foreach (var i in m_Items)
        {
            i.SetBackgroundState(ConditionItem.BackgroundState.Unselect);
        }
        item.SetBackgroundState(ConditionItem.BackgroundState.Selected);

        Sprite sprite = null;
        if (item.m_Sprite != null)
            sprite = item.m_Sprite;
        else
            sprite = ResourcesManager.Instance.GetWeaponsFlyItemSprite(m_Weapon.typeID, item.m_FlyItem.flyItemID);

        if (sprite == null)
            sprite = DrawFlyitemContent.CreateEmptSpriteOfFlyItem();
        item.m_Sprite = sprite;
        m_DrawFlyItemContent.SetSprite(sprite);
        m_SelectedItem = item;
    }
    public void OnAddClicked()
    {
        m_DrawFlyItemContent.m_PaintBoard.Show();
        var flyItem  = m_Weapon.CreateFlyItem();
        var itemUI = AddItem(flyItem);
        SelectedItem(itemUI);
        m_DrawFlyItemContent.m_PaintBoard.ClearUp();
    }
    FlyingItemUI AddItem(FlyItem flyItem)
    {
        var item = Instantiate(m_FlyingItemPrefab);
        item.Init(flyItem);
        item.transform.SetParent(m_Content.transform);
        item.transform.SetSiblingIndex(m_Content.transform.childCount-2);
        item.m_List = this;
        m_Items.Add(item);
        return item;
    }
}